import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { SFSchema } from '@delon/form';
import { ApiService } from '@core/services/api';
import { HttpClient } from '@angular/common/http';
import { NzMessageService, NzModalRef } from 'ng-zorro-antd';
import { UtilService } from '@core/services/util.service';
import { ColumnType, SPage, TablePageComponent } from '@shared/components/table-page/table-page.component';
import { NzTabPosition } from 'ng-zorro-antd/tabs';
import { Router } from '@angular/router';

@Component({
  selector: 'app-landlor-update',
  templateUrl: './landlor-update.component.html',
  styles: []
})
export class LandlorUpdateComponent implements OnInit {
   //房间信息列表
   @ViewChild('st', { static: false }) st: TablePageComponent;
   @ViewChild('tree',{static:false}) tree: any;
   //用户信息
   @Input()type: 0 | 1;
   @Input()
   set _param(value) {
     console.log(value);
     if (!value) return;
     this.param = value;
     this.param.infoAge=this.analyzeIDCard(this.param.papersNumber);
     this.param.infoBirthday=this.getBirthdayFromIdCard(this.param.papersNumber);
     this.param.infoMobile = value.mobile
     if(this.param.infoPeoplePhoto) {
       this.previewImage = this.param.infoPeoplePhoto;
       this.fileList = [...[{
         id: '-1',
         status: 'done',
         url: this.param.infoPeoplePhoto
       }]]
     }

   };
   pIdList:any[]=[];
   defaultCheckedKeys:any=[];
   searchValue:any="";
   previewImage: string | undefined = '';
   previewVisible = false;
   param: any;
   showForm = false;
   checkedList:any[]=[];
   isLoading:boolean=true;
   fileList: any[] = [
     {
       id: '-1',
       status: 'done',
       url: "../../../../../assets/images/noimg.png"
     }
   ];
   houseList = [];
   schema: SFSchema = {
     properties: {
       approveStatus: {
         type: 'string',
         title: '审批状态',
         readOnly:true,
         enum:[
           {label: '未审批', value: "1"},
           {label: '已审批', value: "0"}
         ],
         ui: {
           widget: 'select',
           grid:{span: 8}
         }
       },
       infoName: {
         type: 'string',
         title: '姓名',
         readOnly:true,
         ui: {
           grid: {span: 8}
         }
       },
       papersNumber: {
         type: 'string',
         title: '身份证号',
         readOnly:true,
         ui: {
           grid: {span: 8}
         }
       },
       infoSex: {
         type: 'string',
         title: '性别',
         readOnly:true,
         enum:[
           {label: '女', value: "0"},
           {label: '男', value: "1"},
           {label: '未说明的性别', value: "9"}
         ],
         ui: {
           widget: 'select',
           grid: {span: 8}
         }
       },
       infoAge :{
         type: 'number',
         title: '年龄',
         readOnly:true,
         ui: {
           grid: {span: 8}
         }
       },
       infoBirthday :{
         type: 'string',
         title: '出生日期',
         readOnly:true,
         ui: {
           grid: {span: 8}
         }
       },
       // infoNationCode: {
       //   type: 'string',
       //   title: '民族代码',
       //   ui: {
       //     grid: {span: 6}
       //   }
       // },
       infoNationName: {
         type: 'string',
         title: '民族',
         readOnly:true,
         ui: {
           grid: {span: 8}
         }
       },
       infoMobile: {
         type: 'string',
         title: '联系电话',
         ui: {
           grid: {span: 8}
         }
       },
       // infoEmergencyMobile: {
       //   type: 'string',
       //   title: '紧急联系电话',
       //   ui: {
       //     grid: {span: 8}
       //   }
       // },
       // idCardList2: {
       //   type: 'string',
       //   title: '现居住地址'
       // },
       papersAddress: {
         type: 'string',
         title: '身份证地址',
         readOnly:true,
       }
     },
     "ui": {
       "spanLabelFixed": 150,
       "grid": {
         "span": 24
       }
     },
     required: ['infoMobile']
   }
 
   handlePreview = async () => {
     this.previewVisible = true;
   };
 
   getUserInfo(userId: string): Promise<any>{
     return this.http.request<any>('GET', '/core/person/'+userId).toPromise();
   }

   //提交人员修改数据
   editPerson(data){
    //console.log(data);
    if(data.infoMobile.indexOf("*") != -1){
      this.msg.warning("请输入正确的手机号")
      return
    }
    const body: any = {
      id: data.id,
      infoMobile:data.infoMobile
    };
    console.log(body);
    this.http.post(this.api.user.updatePerson.url,body).subscribe((res:any) => {
      //console.log(res)
      if (res.status === '200' || res.status === '201') {
        this.msg.success('操作成功');
        this.modalRef.triggerOk();
      } else {
        this.msg.error(res.message)
      }
    })
   }


   //提交楼栋修改数据
   formSubmit() {
    let nodes=this.tree.getCheckedNodeList();
    // if(nodes.length == 0){
    //   this.msg.error("请选择楼栋!");
    //   return;
    // }
    let list= this.getCheckedNodes(nodes);
    let list4=this.checkedList.concat(this.pIdList);
    let pIdArr=Array.from(new Set(list4));
//     let list3=this.checkedList;
//     //比较两个对象数组中的元素，将不同的拿出来
//     let result=[];
//     for (var i =  0 ; i < list3.length; i++){
//       var obj = list3[i];
//       var num = obj.id;
//       var isExist =  false ;
//       for (var j =  0 ; j < list.length; j++){
//           var aj = list[j];
//           var n = aj.id;
//           if (n == num){
//               isExist =  true ;
//               break ;
//           }
//       }
//       if (!isExist){
//           obj.id=obj.id+"del";
//           this.pIdList.push(obj.pId);
//           result.push(obj);
//       }
//  }
//  console.log(result);
//     list=list.concat(result);
    let houseManagerList=[];
    for(let item of pIdArr){
      let obj={
        personId:this.param.personId,
        houseId:item,
        roomId:""
      }
      let roomList=[];
      for(let current of list){
        if(item == current.pId){
          roomList.push(current.id);
        }
      }
      obj.roomId=roomList.join(",");
      houseManagerList.push(obj);
    }
    this.http.post(this.api.manager.manageUnit.url,houseManagerList).subscribe((res:any)=>{
      if(res.status == "200"){
        this.msg.success("操作成功");
        this.modalRef.triggerOk();
      }else{
        this.msg.error(res.message);
      }
    })

   }

   resetForm(data){
    this.modalRef.destroy("ok");
   }
   
//扁平化树形数据
getCheckedNodes(checkedNodeList:any){
  let that=this;
  let list=[];
  this.pIdList=[];
  for(let item of checkedNodeList){
    if(item.origin.pId != ""){
     list.push({
        "id":item.origin.id,
        "pId":item.origin.pId
      })
      that.pIdList.push(item.origin.pId);
    }
    if(item.origin.children && item.origin.children.length > 0){
      for(let current of item.origin.children){
        list.push({
          "id":current.id,
          "pId":current.pId
        })
        that.pIdList.push(current.pId);
      }
    }
  }
  return list;
}


   constructor(
     private api: ApiService,
     private http: HttpClient,
     private msg: NzMessageService,
     private modalRef: NzModalRef,
     private util:UtilService,
     private router: Router,
   ) { }
 
   nzTabPosition: NzTabPosition = 'left';
 
   ngOnInit() {
     this.showForm = true;
     this.getHouses();
   }

   selectChage($event){
     //console.log($event);
     //this.router.navigateByUrl("/house-manage");
   }

   //获取被选中的房间
   getlandlordManageUnitList() : void{
     this.http.post(this.api.manager.landlordManageUnitList.url,{personId:this.param.personId}).subscribe((res:any) => {
       console.log(res)
       if (res.status === '200' && res.data && res.data.length > 0) {
         let list=[];
         let list2=[];
         for(let item of res.data){
          list2.push(item.id)
           for(let current of item.roomList){
            list.push(current.id);
           }
         }
         this.defaultCheckedKeys=list;
         this.checkedList=list2;
       } else {
         this.msg.error(res.message);
       }
     })
   }

    //获取楼栋房间列表
  getHouses(): void{
    this.http.post(this.api.manager.queryUnitHouse.url,{"areaParentAllName":""}).subscribe( (res:any) => {
      //console.log(res);
      if (res.status === '200' && res.data && res.data.list.length > 0) {
        let list=[];
        for(let item of res.data.list){
          list.push({
            key:item.id,
            pId:item.areaId == undefined ? "" : item.areaId,
            title:item.areaParentAllName,
            id:item.id,
            value:item.id
          })
          for(let current of item.roomList){
            list.push({
              key:current.id,
              pId:current.areaId,
              title:current.roomNumber == 0 ? current.roomName : ""+current.roomNumber,
              id:current.id,
              value:current.id
            })
          }
        }
        this.houseList=this.util.getTreeNodeOption(list);
        this.getlandlordManageUnitList();
      }
      this.isLoading=false;
    })
  }
     
     

/**
* 根据身份证号精确计算年龄
*/
analyzeIDCard(IDCard:any):Number{
 //获取用户身份证号码
 var userCard = IDCard;
 //如果身份证号码为undefind则返回空
 if(!userCard){
   return;
 }
 //获取出生年月日
 //userCard.substring(6,10) + "-" + userCard.substring(10,12) + "-" + userCard.substring(12,14);
 var yearBirth = userCard.substring(6,10);
 var monthBirth = userCard.substring(10,12);
 var dayBirth = userCard.substring(12,14);
 //获取当前年月日并计算年龄
 var myDate = new Date();
 var monthNow = myDate.getMonth() + 1;
 var dayNow = myDate.getDay();
 var age = myDate.getFullYear() - parseInt(yearBirth);
 monthNow=Number(monthNow);
 monthBirth = parseInt(monthBirth);
 dayNow=Number(dayNow);
 dayBirth=Number(dayBirth);

 if(monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)){
   age--;
 }
 //返回年龄
 return age;
}
//计算生日
getBirthdayFromIdCard(idCard:any):string {
 var birthday = "";
 if(idCard != null && idCard != ""){
   if(idCard.length == 15){
     birthday = "19"+idCard.substr(6,6);
   } else if(idCard.length == 18){
     birthday = idCard.substr(6,8);
   }
   birthday = birthday.replace(/(.{4})(.{2})/,"$1-$2-");
 }
 return birthday;
}
}
